"""
项目信息相关：列表信息
"""

from django.shortcuts import render, HttpResponse, redirect
from sa import models
from django.http import JsonResponse
# 导入分页
from Utils.pagination import Pagination
from datetime import datetime, timedelta
from sa.forms.project_form import ProjectModelForm


def project_list(request):
    if request.method == 'GET':
        # 区分两部分数据 状态 Ongoing 和 Completed
        # 项目参与者也包含
        category = {'ongoing': [], 'completed': []}
        # 反向查询 参与的所有项目
        projects = request.sa.join_projects.all()

        for row in projects:
            if row.status == 'Ongoing':
                category['ongoing'].append(row)
            else:
                category['completed'].append(row)

        # 接收搜索框数据, 空字典
        data_dict = {}
        today = datetime.now().date()
        ago = today - timedelta(days=30)
        search_start_date = request.GET.get('start_d', '')
        search_end_date = request.GET.get('end_d', '')
        find_data = request.GET.get('p_name', '')
        if search_start_date:
            data_dict['start_date__gte'] = search_start_date
        else:
            data_dict['start_date__gte'] = ago

        if search_end_date:
            data_dict['end_date__lte'] = search_end_date
        if search_data:
            data_dict['customer__name__contains'] = find_data

        # queryset = request.sa.join_projects.all()
        queryset = request.sa.join_projects.filter(status='Completed', **data_dict).order_by('-id')

        # 开始页码工具
        page_object = Pagination(request, queryset)
        # 添加项目form
        project_form = ProjectModelForm(request)
        context = {
            'category': category,
            's_date': search_start_date,
            'e_date': search_end_date,
            'search_date': search_data,

            # 分完页的数据
            'queryset': page_object.page_queryset,
            # 计数
            'count': queryset.count(),
            # 生成页码
            'page_string': page_object.html(),

            'form': project_form,
        }

        return render(request, 'my_project.html', context=context)


def search_view(request):
    query = request.GET.get('query', '')
    if query:
        # 有可能是多条记录 要用list()  icontains：不区分大小写
        results = models.Customers.objects.exclude(
            status='1').filter(name__icontains=query).values('id', 'name')
        # return JsonResponse(list(results), safe=False)
        return JsonResponse({'status': True, 'datalist': list(results)})
    else:
        return JsonResponse([])


def search_data(request):
    """ 根据customer_id 获取客户对象 """
    # global global_customer_id       # 将customer_id 赋值给全局变量
    customer_id = request.GET.get('customer_id', '')
    # 检查select_id是否为有效的数字
    if customer_id is None or not customer_id.isdigit():
        # 如果select_id为空或不是数字，返回错误响应
        return JsonResponse({'status': False, 'error': '没有选择客户~.'})

    customer_obj = models.Customers.objects.filter(id=customer_id).first()
    print(customer_obj.name)
    if customer_obj:
        customer_name = customer_obj.name
        return JsonResponse({'status': True, "obj": customer_name})

    else:
        return JsonResponse({'status': False, 'error': 'Customer not found'})
